package com.dianshang.springdataredis;

import com.dianshang.pojo.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

/**
 * Hash类型(Map类型,Key唯一)
 */
@RunWith(SpringJUnit4ClassRunner.class) // Spring整合Redis的核心类
@ContextConfiguration(locations = "classpath:applicationContext-redis.xml") // 上下文配置文件
public class HashDemo {

    @Autowired
    private RedisTemplate redisTemplate;

    // 添加
    @Test
    public void add(){
        User user1 = new User(1,"张三","123");
        User user2 = new User(2,"李四","456");
        User user3 = new User(3,"王五","789");
        redisTemplate.boundHashOps("user").put(user1.getId(), user1);
        redisTemplate.boundHashOps("user").put(user2.getId(), user2);
        redisTemplate.boundHashOps("user").put(user3.getId(), user3);
    }

    // 根据条件查询
    @Test
    public void find(){
        Integer id1 = 1;
        Integer id2 = 2;
        Integer id3 = 3;
        User user1 =(User) redisTemplate.boundHashOps("user").get(id1);
        User user2 =(User) redisTemplate.boundHashOps("user").get(id2);
        User user3 =(User) redisTemplate.boundHashOps("user").get(id3);
        System.out.println(user1);
        System.out.println(user2);
        System.out.println(user3);
    }

    // 根据条件删除
    @Test
    public void delete(){
        Integer id = 1;
        redisTemplate.boundHashOps("user").delete(id);
        // 物理删除
        // redisTemplate.delete("user");
    }

    // 根据条件删除password里面包含4的数据
    @Test
    public void getAll(){
        List<User> users = redisTemplate.boundHashOps("user").values();
        for (User user : users) {
            if (user.getPassword().contains("4")){
                redisTemplate.boundHashOps("user").delete(user.getId());
            }
        }
    }

}